from src.mod import run
from src.utils import mq
from src.core import log
from src.core import Enums
from src.mod import Search
from src.core import Cache
import time, json, re, base64
from src.utils.deep import get_os_info
from src.core.variables.function import *
from src.core.variables.constant import CONF
from src.core.variables.status import (
    ERROR_CODE,
    ERROR_CODE_CUSTOMIZE,
    SUCCESS_CODE,
    SUCCESS_CODE_CUSTOMIZE,
)
from src.schema.hosting import realog_schema
from src.core.variables.constant import MAX_LINES, MAX_HISTORY_LINES
from src.core.variables.cls import HOSTING_JAVA_RUNNER_DICT, HOSTING_STATIC_RUNNER_DICT



# def log_sse(schema: realog_schema):
#     """SSE日志流"""
#     sse_id = CREATE_ID()
#     Cache.SSE_CACHE.set(f"{sse_id}", {"app_id": schema.app_id, "status": True})
#     runner = HOSTING_JAVA_RUNNER_DICT.get(schema.app_id, None)
#     result = json.dumps(
#         {
#             "code": 200,
#             "message": "start",
#             "time": get_os_info.local_time("no week"),
#             "sse_id": sse_id,
#             "app_id": schema.app_id,
#         }
#     )
#     # 发送SSE连接开始消息，避免无内容更新导致的一直在等待状态
#     yield f"data: {result}\n\n"
#     second = 0
#     if runner is not None:
#         match runner.status:
#             case Enums.AppStatus.JAVA_STATUS.DEAD:
#                 # 应用未运行，返回错误信息
#                 while second < CONF.SSE_MAX_TIME:
#                     second += 1
#                     app = Search.Hosting.app_by_id(schema.app_id)
#                     result = json.dumps(
#                         {"code": 401, "message": f"应用[{app.alias}]未启动"}
#                     )
#                     yield f"data: {result}\n\n"
#                     # 服务端主动断开sse连接
#                     break
#             case Enums.AppStatus.JAVA_STATUS.RUNNING:
#                 runner.realog()
#                 while runner.realog_status and second < CONF.SSE_MAX_TIME:
#                     second += 1
#                     time.sleep(1)
#                     log_data, time_data = mq.get(schema.app_id)
#                     if log_data not in [[], None]:                        
#                         for index, value in enumerate(log_data):
#                             msg = re.sub(r'\x1b\[[0-9;]*[mGK]', '', value) + "\n"
#                             result = json.dumps(
#                                 {
#                                     "code": 200,
#                                     "message": base64.b64encode(msg.encode()).decode(),
#                                     "time": time_data[index],
#                                     "sse_id": sse_id,
#                                     "app_id": schema.app_id,
#                                 }
#                             )
#                             yield f"data: {result}\n\n"
#                 # 日志流结束，取消mq订阅
#                 mq.unsubscribe(schema.app_id)
#     else:
#         while True:
#             app = Search.Hosting.app_by_id(schema.app_id)
#             result = json.dumps(
#                 {
#                     "code": 401,
#                     "message": f"无法获取应用[{app.alias}]的运行器，请检查应用状态并尝试重启应用！",
#                 }
#             )
#             yield f"data: {result}\n\n"
#             # 服务端主动断开sse连接
#             break
#     stop_log_sse(schema)


# def stop_log_sse(schema):
#     """停止SSE日志流"""
#     sse_id = CREATE_ID()
#     runner = HOSTING_JAVA_RUNNER_DICT.get(schema.app_id, None)
#     if runner is not None:
#         match runner.status:
#             case Enums.AppStatus.JAVA_STATUS.DEAD:
#                 log.INFO(f"应用[{schema.app_id}]未运行，无法停止日志流")
#                 return ERROR_CODE_CUSTOMIZE(
#                     f"应用[{schema.app_id}]未启动，无法停止日志流", 400
#                 )
#             case Enums.AppStatus.JAVA_STATUS.RUNNING:
#                 runner.stop_realog()
#                 log.INFO(f"已停止应用[{schema.app_id}]的日志流")
#                 Cache.SSE_CACHE.delete(f"{sse_id}")
#                 return SUCCESS_CODE_CUSTOMIZE(
#                     f"应用[{schema.app_id}]实时日志关闭成功！", 200
#                 )
#     else:
#         log.ERROR(
#             f"无法获取应用[{schema.app_id}]的运行器，请检查应用状态并尝试重启应用！"
#         )
#         return ERROR_CODE_CUSTOMIZE(
#             f"无法获取应用[{schema.app_id}]的运行器，请检查应用状态并尝试重启应用！",
#             400,
#         )


def java(schema: realog_schema):
    log_path = Search.Hosting.app_by_id(schema.app_id).log_path
    try:
        offset = int(schema.since)
    except ValueError:
        offset = 0
    if not os.path.exists(log_path):
        return ERROR_CODE.LOG_FILE_NOT_EXISTS({"code": 200, "logs": [], "next_offset": offset})
    lines = []
    new_offset = offset
    with open(log_path, "r") as f:
        # 如果offset为0，表示是首次请求，需要限制历史日志行数
        if offset == 0:
            # 读取所有行
            all_lines = f.readlines()
            # 如果行数超过最大历史日志行数，只取最后的MAX_HISTORY_LINES行
            if len(all_lines) > MAX_HISTORY_LINES:
                all_lines = all_lines[-MAX_HISTORY_LINES:]
                offset = f.tell() - sum(len(line) for line in all_lines)
            lines = [line.rstrip("\n") for line in all_lines]
            new_offset = f.tell()
        else:
            # 非首次请求，按原有逻辑处理
            f.seek(offset)
            for _ in range(MAX_LINES):
                line = f.readline()
                if not line:
                    break
                lines.append(line.rstrip("\n"))
            new_offset = f.tell()
    return SUCCESS_CODE.LOG_CONTEXT({
        "code": 200,
        "logs": lines,
        "next_offset": new_offset
    })
